package com.zysd.collection.scheduler.controller;

import cn.uncode.schedule.ConsoleManager;
import cn.uncode.schedule.core.TaskDefine;
import com.lensyn.common.utils.system.response.Response;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 定时任务管理 Controller
 *
 * @author liuht
 * @date 2017/10/11 14:53
 */

@RestController
@RequestMapping("/scheduler")
public class SchedulerManagerController {

    /**
     * 获取所有定时任务
     */
    @GetMapping("/schedulers")
    public Response getAllSchedulers() {
        List<TaskDefine> tasks = ConsoleManager.queryScheduleTask();
        return new Response<>().success(tasks);
    }

    /**
     * 获取所有 集群节点
     */
    @GetMapping("/servers")
    public Response getAllSchedulerServers() throws Exception {
        List<String> serversNames = ConsoleManager.getSchedulerTaskManager().getSchedulerServer().loadScheduleServerNames();
        List<Map<String, String>> servers = new ArrayList<>(serversNames.size());
        for (String name : serversNames) {
            Map<String, String> server = new HashMap<>(serversNames.size());
            server.put("name", name);
            if (ConsoleManager.getSchedulerTaskManager().getSchedulerServer().isLeader(name, serversNames)) {
                server.put("isLeader", "是");
            } else {
                server.put("isLeader", "否");
            }
            servers.add(server);
        }
        return new Response<>().success(servers);
    }

    /**
     * 删除指定定时任务
     */
    @DeleteMapping("/delete")
    public Response deleteScheduler(@RequestBody TaskDefine taskDefine) {
        ConsoleManager.delScheduleTask(taskDefine);
        return new Response<>().success();
    }

    /**
     * 添加指定定时任务
     */
    @PostMapping("/add")
    public Response addScheduler(@RequestBody TaskDefine taskDefine) {
        taskDefine.setStartTime(new Date());
        if(StringUtils.isNotEmpty(taskDefine.getCronExpression()) || StringUtils.isNotEmpty(taskDefine.getPeriod()+"")){
            ConsoleManager.addScheduleTask(taskDefine);
        }
        return new Response<>().success();
    }

    /**
     * 停止指定定时任务
     */
    @PatchMapping("/stop")
    public Response stopScheduler(@RequestBody TaskDefine taskDefine) {
        taskDefine.setStatus(TaskDefine.STATUS_STOP);
        ConsoleManager.updateScheduleTask(taskDefine);
        return new Response<>().success();
    }

    /**
     * 开启指定定时任务
     */
    @PatchMapping("/start")
    public Response startScheduler(@RequestBody TaskDefine taskDefine) {
        taskDefine.setStatus(TaskDefine.STATUS_RUNNING);
        ConsoleManager.updateScheduleTask(taskDefine);
        return new Response<>().success();
    }
}
